package userController

import (
	"bookStore/global"
	"bookStore/model"
	"bookStore/service/userService"
	"bookStore/util/contextUtils"
	"bookStore/util/stringUtils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func Login(context *gin.Context) {
	var user model.User
	context.BindJSON(&user)
	if user.IsEmpty() || user.Name == "" || user.Password == "" {
		contextUtils.ErrorJSON(context, http.StatusBadRequest, "用户名或密码不能为空")
	}
	resUser, cookie, err := userService.Login(user.Name, user.Password)
	if err != nil {
		contextUtils.ErrorJSON(context, http.StatusBadRequest, err.Error())
	} else {
		context.SetCookie(global.CookieKey, cookie, 60, "/", "", false, true)
		context.Header("Cookie", cookie)
		contextUtils.OkJSON(context, resUser)
	}
}

func AddUser(ctx *gin.Context) {
	var user model.User
	ctx.BindJSON(&user)
	err := userService.AddUser(&user)
	if err != nil {
		contextUtils.ErrorJSON(ctx, http.StatusBadRequest, err.Error())
	} else {
		contextUtils.OkJSON(ctx, user)
	}
}

func BatchAddUser(ctx *gin.Context) {
	var users = make([]model.User, 0)
	ctx.BindJSON(&users)
	err := userService.BatchAddUser(users)
	if err != nil {
		contextUtils.ErrorJSON(ctx, http.StatusBadRequest, err.Error())
	} else {
		contextUtils.OkJSON(ctx, users)
	}
}

func FindUserById(ctx *gin.Context) {
	userIdStr := ctx.Query("userId")
	if stringUtils.IsBlank(userIdStr) {
		contextUtils.ErrorJSON(ctx, http.StatusBadRequest, "被查询用户的userId字段不能为空")
	} else {
		userId, err := strconv.ParseInt(userIdStr, 10, 64)
		if err != nil {
			contextUtils.ErrorJSON(ctx, http.StatusBadRequest, "被查询用户的userId字段传值错误")
		} else {
			user := userService.FindUserById(userId)
			contextUtils.OkJSON(ctx, user)
		}
	}
}
